package com.tang.portal.facade;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tang.common.constant.Constant;
import com.tang.framework.core.domain.HttpResult;
import com.tang.framework.core.model.LoginUser;
import com.tang.common.model.req.ReqId;
import com.tang.common.model.req.ReqIds;
import com.tang.common.exception.BusinessException;
import com.tang.common.exception.eumes.Error;
import com.tang.service.account.domain.BaseUser;
import com.tang.service.account.model.req.ReqBaseUser;
import com.tang.service.account.model.req.ReqBaseUserAdd;
import com.tang.service.account.model.res.ResBaseUser;
import com.tang.service.account.model.res.ResBaseUserDetail;
import com.tang.service.account.service.IBaseUserService;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.tang.common.utils.excel.ExcelUtils.getStyleStrategy;

/**
 * @author tang jun liang
 * @Date 2023-4-3 09:04:00
 */
@Service
public class BaseUserFacade {

    @Resource
    private IBaseUserService baseUserService;


    /**
     * 基本用户表删除
     *
     * @param id
     * @param currLoginUser
     * @return
     */
    public HttpResult<String> remove(ReqId id, LoginUser currLoginUser) {
        baseUserService.removeById(id.getId());
        return HttpResult.ok();
    }

    /**
     * 基本用户表详情
     *
     * @param id
     * @param currLoginUser
     * @return
     */
    public HttpResult<ResBaseUserDetail> detail(ReqId id, LoginUser currLoginUser) {
        BaseUser baseUser = baseUserService.getById(id.getId());
        ResBaseUserDetail resBaseUserDetail = new ResBaseUserDetail();
        BeanUtils.copyProperties(baseUser, resBaseUserDetail);
        return HttpResult.ok(resBaseUserDetail);
    }

    /**
     * 基本用户表列表
     *
     * @param reqBaseUser
     * @param currLoginUser
     * @return
     */
    public HttpResult<IPage<ResBaseUser>> list(ReqBaseUser reqBaseUser, LoginUser currLoginUser) {

        //todo 待实现
        throw new BusinessException(Error.NOT_IMPLEMENTED);
    }

    /**
     * 新增基本用户表
     *
     * @param baseUserAdd
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    public HttpResult<String> add(ReqBaseUserAdd baseUserAdd) {
        BaseUser baseUser = new BaseUser();
        BeanUtils.copyProperties(baseUserAdd, baseUser);
        baseUserService.saveOrUpdate(baseUser);
        return HttpResult.ok();
    }

    /**
     * 更新基本用户表
     *
     * @param baseUserAdd
     * @return
     */
    public HttpResult<String> update(ReqBaseUserAdd baseUserAdd) {
        return add(baseUserAdd);
    }

    /**
     * 导出基本用户表
     *
     * @param ids
     * @param httpServletResponse
     */
    @SneakyThrows
    public void export(ReqIds ids, HttpServletResponse httpServletResponse) {
        String fileName = URLEncoder.encode("基本用户.xlsx", StandardCharsets.UTF_8);
        // 设置响应体
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName);
        List<BaseUser> baseUserList = baseUserService
                .lambdaQuery()
                .in(!ids.getIds().isEmpty(), BaseUser::getId, ids.getIds())
                .list();
        EasyExcel.write(httpServletResponse.getOutputStream())
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(getStyleStrategy())
                .sheet("基本用户").doWrite(baseUserList);
    }

    /**
     * 导入excel
     *
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult<String> importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, ReqBaseUserAdd.class, new AnalysisEventListener<ReqBaseUserAdd>() {
            final List<BaseUser> baseUserList = new ArrayList<>();
            @Override
            public void invoke(ReqBaseUserAdd baseUserAdd, AnalysisContext analysisContext) {
                BaseUser baseUser = new BaseUser();
                BeanUtils.copyProperties(baseUserAdd, baseUser);
                baseUserList.add(baseUser);
                if (baseUserList.size() == Constant.MAX_BATCH){
                    baseUserService.saveBatch(baseUserList);
                    baseUserList.clear();
                }
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                baseUserService.saveBatch(baseUserList);
            }
        });
        return HttpResult.ok();
    }

    /**
     * 导出模版
     * @param httpServletResponse
     */
    @SneakyThrows
    public void exportTemplate(HttpServletResponse httpServletResponse) {
        String fileName = URLEncoder.encode("基本用户导入模版.xlsx", StandardCharsets.UTF_8);
        // 设置响应体
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName);
        EasyExcel.write(httpServletResponse.getOutputStream())
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(getStyleStrategy())
                .sheet("基本用户").doWrite(List.of());
    }



}
